package com.orifine.orm.mysql;

import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.orifine.orm.SqlScriptGenerator;
import com.orifine.orm.TypeManager;
import com.orifine.orm.model.DatabaseModel;
import com.orifine.orm.model.TableModel;
import com.orifine.orm.type.BooleanType;
import com.orifine.orm.type.DateType;
import com.orifine.orm.type.Int;
import com.orifine.orm.type.StringType;
import com.orifine.orm.type.TimeType;
import com.orifine.orm.type.TimestampType;



public class MySqlScriptGenerator implements SqlScriptGenerator {
	
	private Map<Class<?>, TableModel> tableClassMap = new HashMap<Class<?>, TableModel>();
	private DatabaseModel database = new DatabaseModel();
	private int infoMaxSize = 100;
	
	public MySqlScriptGenerator(){
		initType();
	}
	
	@Override
	public void setDatabase(String database) {
		this.database.setName(database);
	}

	@Override
	public void addTables(Set<Class<?>> tableClasses) {
		for(Class<?> tableClass : tableClasses){
			addTable(tableClass);
		}
		
	}
	
	@Override
	public void addTable(Class<?> tableClass){
		TableModel table = database.getTable(tableClass);
		if(table != null){
			table.getColumns();
			tableClassMap.put(tableClass, table);
		}
	}
	
	@Override
	public void setInfoMaxSize(int size){
		this.infoMaxSize = size;
	}
	
	@Override
	public List<String> sqlList() {
		MySqlStringBuffer out = new MySqlStringBuffer();
		
		out.setForeignKeyChecks(false);
		
		if(database.getName() != null){
			out.dropDatabase(database.getName());
			out.createDatabase(database.getName());
			out.useDatabase(database.getName());
			out.go();
		}
		
		for(TableModel tableModel : tableClassMap.values()){
			out.createTable(tableModel);
			out.insertInto(tableModel, infoMaxSize);
		}
		out.go();
		
		out.setForeignKeyChecks(true);
		return out.getList();
	}
	
	public void initType(){
		TypeManager.register(boolean.class, BooleanType.class);
		
		TypeManager.register(Boolean.class, BooleanType.class);
		
		TypeManager.register(Integer.class, Int.class);
		
		TypeManager.register(int.class, Int.class);
		
		TypeManager.register(String.class, StringType.class);
		
		TypeManager.register(Date.class, DateType.class);
		
		TypeManager.register(Time.class, TimeType.class);
		
		TypeManager.register(Timestamp.class, TimestampType.class);
	}
}
